//index.js
//获取应用实例
const app = getApp()
import {
  getInfo,
} from '../../../api/member'

import {
  unReadCount,
} from '../../../api/msgPush'

import {
  couponCount
} from '../../../api/coupon'

import {
  traceCount
} from '../../../api/trace'

import {
  favoritesCount
} from '../../../api/favorite'
import {
  summary
} from '../../../api/giftCard'
import {
  getInfo as mchGetInfo
} from '../../../api/enterprise'
import {
  getVIP
} from '../../../api/superVip'
import {
  createQrcode
} from '../../../api/member'
import css2canvas from "../../../utils/css2canvas"
const util = require('../../../utils/util.js')

Page({
  data: {
    noToken: true,
    haveAvatarUrl: false,
    name: "",
    vip: "",
    giftNumber: '',
    favoriteNum: 0, //收藏数
    footprint: 0, //足迹
    couponNum: 0, //优惠券数量
    statusBarHeight: "", //顶部的 高度
    avatar: "", //头像链接
    unReadNum: 0, //未读消息数
    showUnReadNum: "", //显示的未读数量
    mch: null,
    point: '',
    vipType: false,
    codeType: false,
    qrcode: '',
    qrCodeImg: '',
    canvasType: false,
    cardInfo: {
      TagText: "****", //标签
      Name: '****', //姓名
      avater: "", //需要https图片路径
      qrCode: "", //需要https图片路径
      price: '**',
      logo: 'http://cdnx.rzico.com/images/canvasMyLogo.png',
      coupons: '',
      marketPrice: '',
      activityPrice: ''
    },
    canvasHeight: 400,
    canvasH: 0,
    carvasQrCode: '',
    carvasLogo: '',
    vipMemo:[],
    SCOPE_TYPE:1,
    Invitationcode:"",
    GIFT_TYPE:0
  },

  onLoad: function () {
    this.data.canvasH = (wx.getSystemInfoSync().windowWidth / 750).toFixed(2)
    this.data.canvasHeight = 500 * this.data.canvasH
    this.data.SCOPE_TYPE=app.SCOPE_TYPE
    this.data.GIFT_TYPE=app.GIFT_TYPE
    this.setData({
      VERSION: app.VERSION,
      statusBarHeight: app.globalData.statusBarHeight,
      canvasHeight: this.data.canvasHeight,
      SCOPE_TYPE: app.SCOPE_TYPE,
      GIFT_TYPE: app.GIFT_TYPE,
    })
    this.createQrcodeClick()
  },

  onShow: function () {
    if (app.globalData.token != "" && app.globalData.token != null) {
      this.setData({
        noToken: false
      })
    }
    const {
      userInfo
    } = app.globalData
    if (userInfo) {
      //怎么判断是否已经头像授权
      if (userInfo.hasOwnProperty("avatar")) {
        this.setData({
          haveAvatarUrl: true,
          avatar: app.globalData.userInfo.avatar,
          name: app.globalData.userInfo.nickname,
        })
      }
    }
    this.getGift()
    this.getunReadCount()
    this.getcouponCount()
    this.getTraceCount()
    this.getFavoritesCount()
    this.getVIPClick()
    this.getInfo()
    this.getInfoClick()
  },
  copeINV(){
    wx.setClipboardData({
      data: this.data.Invitationcode,
      success (res) {
        wx.getClipboardData({
          success (res) {
            console.log(res.data) // data
            wx.showToast({
              title: '复制成功',
              icon:'none'
            })
          }
        })
      }
    })
  },
  getGift() {
    summary().then(res => {
      this.data.giftNumber = (res.data.mycount + res.data.rvcount)
      this.setData({
        giftNumber: this.data.giftNumber
      })
    })
  },
  getcouponCount() {
    couponCount().then(
      res => {
        console.log("接收优惠券的数量--" + JSON.stringify(res))
        if (res.type == 'success') {
          this.setData({
            couponNum: res.data
          })
        }
      }
    ).catch(error => {

    })
  },

  getTraceCount() {
    traceCount().then(
      res => {
        console.log("接收足迹的数量--" + JSON.stringify(res))
        if (res.type == 'success') {
          this.setData({
            footprint: res.data
          })
        }
      }
    ).catch(error => {

    })
  },

  getFavoritesCount() {
    favoritesCount().then(
      res => {
        console.log("接收收藏的数量--" + JSON.stringify(res))
        if (res.type == 'success') {
          this.setData({
            favoriteNum: res.data
          })
        }
      }
    ).catch(error => {

    })
  },

  //获取用户未读信息数量
  getunReadCount() {
    unReadCount().then(
      res => {
        console.log("接收用户信息--" + JSON.stringify(res))
        if (res.type == 'success') {
          let unReadNum = 0
          if (res.data.length > 0) {
            res.data.map(item => {
              unReadNum += item.msg_num
            })
          }
          this.setData({
            unReadNum: unReadNum,
            showUnReadNum: unReadNum > 100 ? '...' : unReadNum
          })
          console.log("unReadNum--" + this.data.unReadNum)
        }
      }
    ).catch(error => {

    })
  },

  //获取用户信息
  getInfo() {
    var _this = this
    getInfo().then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          this.data.Invitationcode=Number(res.data.member.id)+10200
          this.setData({
            vip: util.isNull(res.data.member.vipName) ? "vip" + res.data.member.vip : res.data.member.vipName,
            point: res.data.point,
            Invitationcode:this.data.Invitationcode
          })
          console.log(res.data.point)
        }
      }
    ).catch(error => {
      console.log(error)
    })
  },

  //检测用户的登陆状态
  checkLogin(callback) {
    console.info("全局变量app.globalData--" + JSON.stringify(app.globalData))
    if (app.globalData.token == null) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
    } else {
      if (callback) {
        callback()
      }
    }
  },
  //我的礼卡
  toGiftCard() {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/giftCard/giftCard',
      })
    })
  },
  //旅游卡

  totouristCard() {
    this.checkLogin(() => {
      wx.navigateTo({
        url:'/pages/touristCard/touristCard',
      })
    })
  },
  //激活旅游卡
  toUseactivation(e){
    wx.navigateTo({
      url:'/pages/touristCard/activation/activation'
      })
  },
  //分销中心
  toDistribution() {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/distribution/distribution',
      })
    })
  },
  //跳转到个人资料的页面
  toPersonInfo: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/personInfo/personInfo',
      })
    })
  },

  //收藏夹
  toFavorite: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/favorite/favorite',
      })
    })
  },

  //足迹
  toFootprint: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/footprint/footprint',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })
  },

  //优惠券
  toCoupon: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/coupon/coupon',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })

  },

  //收货地址
  toAddress: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/address/address',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })
  },

  // 推广中心
  toShareCenter: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/shareCenter/shareCenter',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })
  },

  // 新手指引
  toNoviceGuide() {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/noviceGuide/noviceGuide',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })
  },

  //常见问题
  toQuestion: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/commonProblem/commonProblem',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })
  },

  //留言咨询
  toConsultation: function (e) {
    this.checkLogin(() => {
      // wx.navigateTo({
      //         url: '/pages/member/consultation/consultation',
      // })
    })
  },

  //消息通知
  toMessage: function (e) {
    this.checkLogin(() => { })
  },

  //系统设置
  toSet: function (e) {
    this.checkLogin(() => { })
  },

  //关于我们
  toUs: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/aboutUs/aboutUs',
        // url: '/pages/goods/category/category',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })

  },

  messageClick() {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/message/index',
      })
    })

  },
  toCall() {
    let _this = this
    console.info()
    if (_this.data.mch.phone) {
      wx.makePhoneCall({
        phoneNumber: _this.data.mch.phone // 仅为示例，并非真实的电话号码
      })
    }
  },
  handleContact(e) {
    // console.log('aaaa')
  //  if(this.data.mch.phone!=''){
  //   wx.makePhoneCall({
  //     phoneNumber: this.data.mch.phone
  //   })
  //   return
  //  }


  },

  getInfoClick() {
    let _this = this
    console.info("我被执行了")
    mchGetInfo({ "mchId": app.globalData.mchId }).then(
      res => {
        console.log(res)
        if (res.type == 'success') {

          _this.data.mch = res.data
          _this.setData({
            mch: _this.data.mch
          })
        }
      }
    ).catch(error => {
      console.log(error)
    })
  },
  toAmap() {
    var _this = this
    wx.navigateTo({
      url: '/pages/index/amap',
    })
  },
  // 会员
  vipClick() {
      wx.navigateTo({
        url: '/pages/member/vip/myVip',
      })
  },
  getVIPClick() {
    var _this = this
    getVIP().then(
      res => {
        console.log(res)
        if (res.data.vip != null) {
          console.log('1111')
          _this.data.vipType = true
          _this.data.vipMethod = res.data.vip.method;
          _this.data.vipName = res.data.vip.name
          console.log('会员公告')
          _this.data.vipMemo = res.data.vip.memo.split(/[(\r\n)\r\n]+/);
          _this.data.vipMemo.forEach(function (item, index) {
            if (!item) {
              _this.data.vipMemo.splice(index, 1);
            }
          })
          _this.setData({
            vipType: _this.data.vipType,
            vipName: _this.data.vipName,
            vipMemo: _this.data.vipMemo
          })
        } else {
          _this.data.vipType = false
          _this.setData({
            vipType: _this.data.vipType,
          })
        }
      }
    ).catch(error => {
      console.log(error)
    })
  },
  // codeClick(){
  //   this.createQrcodeClick()
  //   this.data.codeType = !this.data.codeType
  //   this.setData({
  //     codeType:this.data.codeType
  //   })
  // },
  cancelCode() {
    this.data.codeType = !this.data.codeType
    this.setData({
      codeType: this.data.codeType
    })
  },
  // createQrcodeClick() {
  //   if (app.globalData.token == null) {
  //     return;
  //   }
  //   createQrcode().then(res => {
  //     this.data.qrcode =  res.content
  //     this.createImageClick()
  //   }).catch(error => {

  //   })
  // },
  // createImageClick() {
  //   let data =  this.data.qrcode
  //   this.data.qrCodeImg = app.APP_BASE_API + '/zxing/createImage?mchId='+app.globalData.mchId+'&data='+encodeURIComponent(data)
  //   this.setData({
  //     qrCodeImg: this.data.qrCodeImg
  //   })
  // },
  canvasClick() {
    var _this = this
    this.data.canvasType = true
    wx.getImageInfo({
      src: _this.data.cardInfo.qrCode, //网络图片路径
      success: res => {
        console.log(res.path, 's2')
        _this.data.carvasQrCode = res.path; //图片临时本地路径
        wx.getImageInfo({
          src: util.proxyImage(app.APP_BASE_API, util.thumbnail('http://cdn.rzico.com/img/fenxiang.png', 400, 400)), //网络图片路径
          success: res => {
            console.log(res.path, 's2')
            _this.data.carvasLogo = res.path; //图片临时本地路径
            _this.setData({
              canvasType: _this.data.canvasType,
              cardInfo: _this.data.cardInfo
            })
            setTimeout(function () {
              _this.sharePosteCanvas()
            }, 1000)
          }
        })

      }
    })

  },
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'canvas-show',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  },
  createQrcodeClick() {
    if (app.globalData.token == null) {
      return;
    }
    createQrcode().then(res => {
      this.data.qrcode = res.content
      this.createImageClick()
    }).catch(error => {

    })
  },
  cancleCanvasClick() {
    this.data.canvasType = false
    this.setData({
      canvasType: this.data.canvasType
    })
  },
  createImageClick() {
    let data = this.data.qrcode
    this.data.cardInfo.qrCode = app.APP_BASE_API + '/zxing/createImage?mchId=' + app.globalData.mchId + '&data=' + encodeURIComponent(data)
    console.log(this.data.cardInfo.qrCode)
    this.setData({
      cardInfo: this.data.cardInfo
    })
  },
  sharePosteCanvas: function () {
    var _this = this
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    var canvasShow = wx.createCanvasContext("canvas-show")
    let ctx = new css2canvas(canvasShow)
    var canvasForm = [
      {
        type: "roundRect",
        x: 0,
        y: 0,
        width: 550,
        height: 500,
        background: "#ffffff",
        borderWidth: 1,
        borderRadius: 0,
        clip: false
      },
      {
        type: "image",
        imgUrl: _this.data.carvasQrCode,
        x: 20,
        y: 20,
        width: 400,
        height: 400
      },
      {
        type: "image",
        imgUrl: _this.data.carvasLogo,
        x: 60,
        y: 430,
        width: 40,
        height: 40
      },
      {
        type: "text",
        x: 112,
        y: 436,
        width: 320,
        content: '微信扫一扫，进入小程序',
        color: "#666666",
        fontSize: 24,
        textAlign: "left",
        overflow: "warp",
        maxLine: 1,
        lineHeight: 1
      },

    ]
    ctx
      .drawingView(canvasForm)
      .then(res => {
        console.log("绘制完成")
        wx.hideLoading();
      })
  },
  myCatchTouch: function () {
    console.log('stop user scroll it!');
    return;
},
})
